<template>
  <div class="article">
    <nav-bar>
      <div
        class="del-btn"
        v-if="userStore.user?.id === article?.userId"
        @click="onDelete"
      >
        删除
      </div>
    </nav-bar>
    <van-skeleton avatar title :loading="skeletonLoading" :row="16">
      <div class="title">{{ article?.name }}</div>
      <header-user
        v-if="article"
        :user="article.user"
        :time="article.updateTime"
      />
      <div class="content">{{ article?.content }}</div>
      <div class="imgs">
        <template v-for="(item, index) in article?.imgList" :key="item">
          <van-image
            width="100%"
            :src="item"
            radius="10"
            @click="onClickImage(index)"
          />
        </template>
      </div>
      <van-divider />
    </van-skeleton>
    <comment-list
      ref="commentListRef"
      v-if="article?.id"
      :article-id="article?.id"
      @reply-comment="getReplyComment"
      @push-reply-data="getReplyData"
    />
    <div class="bottom" :style="{ zIndex: zIndex }">
      <div class="tip" v-if="commentContent">
        <div class="van-ellipsis message">回复给:{{ commentContent }}</div>
        <van-button size="mini" @click="onCancelReply">取消</van-button>
      </div>
      <van-cell-group>
        <van-field
          v-if="!isShowField"
          class="input"
          @click-input="onClickInput"
          placeholder="输入你想说的内容"
        >
          <template #button>
            <van-icon
              v-if="isStar"
              name="star"
              color="#88c4fc"
              @click="onRemoveStar"
            />
            <van-icon v-else name="star-o" color="#88c4fc" @click="onAddStar" />
          </template>
        </van-field>
        <van-field
          v-if="isShowField"
          ref="commentValRef"
          class="input"
          v-model="commentVal"
          placeholder="输入你想说的内容"
          clearable
          autosize
          rows="3"
          type="textarea"
          @blur="onBlurField"
        >
          <template #button>
            <van-button
              class="btn"
              size="small"
              round
              type="primary"
              @click="onPushMsg"
              >发送</van-button
            >
          </template>
        </van-field>
      </van-cell-group>
    </div>
  </div>
</template>

<script setup lang="ts">
import NavBar from '../../../components/nav-bar.vue'
import { getArticleDetail, removeArticleById } from '../../../service/article'
import { articleDetailRes } from '../../../service/article/types'
import HeaderUser from '../../../components/header-user.vue'
import CommentList from './components/comment-list.vue'
import { createComment, createCommentReply } from '../../../service/comment'
import { Dialog, FieldInstance, ImagePreview, Notify, Toast } from 'vant'
import { commentsRes, replysRes } from '../../../service/comment/types'
import { useUserStore } from '../../../store/user'
import {
  addStar,
  getIsStar,
  removeStarByArticleId
} from '../../../service/star'
import { userDetail } from '../../../service/user/types'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const commentValRef = ref<FieldInstance>()
const article = ref<articleDetailRes.Article>()
const commentVal = ref<string>('')
const commentListRef = ref<InstanceType<typeof CommentList>>()
const commentContent = ref<string>()
const commentId = ref<number>(0)
const replyId = ref<number | null>(null)
const toUserId = ref<number>(0)
const zIndex = ref<number>(0)
const isShowField = ref<boolean>(false)
const skeletonLoading = ref<boolean>(true)
const isStar = ref<boolean>(false)
const replyUser = ref<userDetail.User>()

const onRemoveStar = async () => {
  if (!article.value) return
  const res = await removeStarByArticleId(article.value.id)
  if (res) {
    Toast('移除收藏成功~')
    isStar.value = false
  }
}
const onAddStar = async () => {
  if (!article.value) return
  const res = await addStar(article.value.id)
  if (res) {
    Toast('添加收藏成功~')
    isStar.value = true
  }
}
const onDelete = () => {
  Dialog.confirm({
    message: '确认删除该文章吗?',
    confirmButtonColor: '#228efc'
  }).then(async () => {
    if (!article.value) return
    const res = await removeArticleById(article.value?.id)
    if (res) {
      Notify({
        message: '删除成功~',
        type: 'success'
      })
      router.back()
    }
  })
}
const onClickImage = (index: number) => {
  if (!article.value) return
  ImagePreview({
    images: article.value.imgList,
    startPosition: index
  })
}
const onCancelReply = () => {
  doSomething()
}
const onBlurField = () => {
  if (!commentVal.value) {
    doSomething()
  }
}
const onClickInput = () => {
  isShowField.value = true
  setTimeout(() => {
    commentValRef.value?.focus()
  }, 50)
}
const getReplyData = (item: replysRes.Reply) => {
  commentId.value = item.commentId
  replyUser.value = item.fromUser
  replyId.value = item.id
  toUserId.value = item.fromUserId
  commentContent.value = item.content
  zIndex.value = 9999
  isShowField.value = true
  setTimeout(() => {
    commentValRef.value?.focus()
  }, 50)
}
const getReplyComment = (comment: Partial<commentsRes.Comment>) => {
  commentContent.value = comment.content
  replyUser.value = comment.user
  if (!comment.fromUserId) return
  toUserId.value = comment.fromUserId
  if (!comment.id) return
  commentId.value = comment.id
  isShowField.value = true
  setTimeout(() => {
    commentValRef.value?.focus()
  }, 50)
}
const onPushMsg = async () => {
  if (commentVal.value === '') {
    Toast('请输入内容哦!')
    return
  }
  if (commentContent.value) {
    const res = await createCommentReply(
      commentId.value,
      commentVal.value,
      replyId.value,
      toUserId.value
    )
    if (!commentListRef.value) return
    for (let i = 0; i < commentListRef.value.list.length; i++) {
      if (commentListRef.value.list[i].id === commentId.value) {
        let count = commentListRef.value.list[i].replyCount
        if (typeof count === 'undefined') count = 0
        commentListRef.value.list[i].replyCount = count + 1
        if (!userStore.user || !replyUser.value) return
        commentListRef.value.replyRef?.list.push({
          ...res.data.reply,
          toUser: replyUser.value,
          fromUser: userStore.user
        })
      }
    }
  } else {
    if (!article.value) return
    const res = await createComment(article.value?.id, commentVal.value)
    if (!commentListRef.value) return
    if (commentListRef.value.list.length >= commentListRef.value.totalCount) {
      commentListRef.value.list.push({
        ...res.data.comment,
        user: userStore.user
      })
    }
  }
  Toast('发布成功~')
  doSomething()
}
const doSomething = () => {
  commentVal.value = ''
  commentContent.value = ''
  replyId.value = null
  zIndex.value = 0
  isShowField.value = false
}
const loadArticle = async () => {
  const id = route.params.id
  const res = await getArticleDetail(id as unknown as number)
  article.value = res.data.article
}
const loadIsStar = async () => {
  const token = localStorage.getItem('token')
  if (!token) return
  if (!article.value) return
  const res = await getIsStar(article.value.id)
  isStar.value = res.data.isStar
}
onMounted(() => {
  loadArticle().then(() => {
    loadIsStar().then(() => {
      skeletonLoading.value = false
    })
  })
})
</script>

<style lang="scss" scoped>
.article {
  padding: 0 15px;
  padding-bottom: 10px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 52px;
  overflow: auto;
  background-color: #fff;
  .del-btn {
    color: #48a0fc;
  }
  .title {
    margin-top: 5px;
    color: var(--van-text-color);
    font-size: 16px;
    font-weight: 600;
  }
  .content {
    white-space: break-spaces;
    margin-bottom: 5px;
    color: var(--van-gray-8);
  }
  .bottom {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    .input {
      :deep(.van-icon) {
        font-size: 18px;
      }
    }
    .tip {
      background-color: #fff;
      padding: 5px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .message {
        flex: 1;
      }
      .van-button {
        width: 35px;
      }
    }
    .btn {
      width: 55px;
    }
  }
}
</style>
